<template>
  <PageContainer
    title="用户管理"
    :actions="pageActions"
    :columns="columns"
    :data-source="userList"
    :loading="loading"
    :pagination-data="pagination"
    @search="handleSearch"
    @reset="handleReset"
    @pagination-change="handlePaginationChange"
  >
    <!-- 筛选条件 -->
    <template #filter-items>
      <a-form-item label="用户状态">
        <a-select
          v-model:value="queryParams.status"
          placeholder="全部状态"
          style="width: 150px"
          allowClear
        >
          <a-select-option :value="undefined">全部</a-select-option>
          <a-select-option :value="1">启用</a-select-option>
          <a-select-option :value="0">禁用</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="关键词">
        <a-input
          v-model:value="queryParams.keyword"
          placeholder="用户名、姓名、手机号"
          style="width: 200px"
          allowClear
        />
      </a-form-item>
    </template>

    <!-- 表格内容 -->
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'username'">
        <div style="font-weight: 500">{{ record.username }}</div>
        <div class="user-email">{{ record.email || "-" }}</div>
      </template>

      <template v-else-if="column.key === 'realName'">
        <div>{{ record.realName }}</div>
        <div class="user-phone">{{ record.phone || "-" }}</div>
      </template>

      <template v-else-if="column.key === 'roleName'">
        <a-tag v-if="isAdminUser(record)" color="purple">
          {{ record.roleName }}
        </a-tag>
        <a-tag v-else color="blue">{{ record.roleName || "未分配" }}</a-tag>
      </template>

      <template v-else-if="column.key === 'status'">
        <a-tag :color="record.status === 1 ? 'green' : 'red'">
          {{ record.status === 1 ? "启用" : "禁用" }}
        </a-tag>
      </template>

      <template v-else-if="column.key === 'lastLoginTime'">
        {{ formatDateTime(record.lastLoginTime) }}
      </template>

      <template v-else-if="column.key === 'action'">
        <template v-if="isAdminUser(record)">
          <a-space>
            <a-button
              type="link"
              size="small"
              @click="handleResetPassword(record)"
              v-permission="'x3w9l2k7'"
            >
              重置密码
            </a-button>
          </a-space>
          <div class="admin-tip">
            <small style="color: var(--text-secondary)"
              >系统管理员账号，仅可重置密码</small
            >
          </div>
        </template>
        <a-space v-else>
          <a-button
            type="link"
            size="small"
            @click="handleEdit(record)"
            v-permission="'v2h7m9c5'"
          >
            编辑
          </a-button>
          <a-button
            type="link"
            size="small"
            @click="handleResetPassword(record)"
            v-permission="'x3w9l2k7'"
          >
            重置密码
          </a-button>
          <a-button
            type="link"
            size="small"
            @click="handleToggleStatus(record)"
            v-permission="'v2h7m9c5'"
          >
            {{ record.status === 1 ? "禁用" : "启用" }}
          </a-button>
          <a-popconfirm
            title="确定删除此用户吗？"
            @confirm="handleDelete(record.id)"
            v-permission="'z6t4q8r1'"
          >
            <a-button type="link" size="small" danger> 删除 </a-button>
          </a-popconfirm>
        </a-space>
      </template>
    </template>
  </PageContainer>

  <!-- 新增/编辑用户弹窗 -->
  <a-modal
    v-model:open="modalVisible"
    :title="modalTitle"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :width="600"
  >
    <a-form
      :model="formData"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
    >
      <a-form-item label="用户名" required>
        <a-input
          v-model:value="formData.username"
          placeholder="请输入用户名"
          :disabled="isEdit"
        />
      </a-form-item>
      <a-form-item v-if="!isEdit" label="密码" required>
        <a-input-password
          v-model:value="formData.password"
          placeholder="请输入密码"
        />
      </a-form-item>
      <a-form-item label="真实姓名" required>
        <a-input
          v-model:value="formData.realName"
          placeholder="请输入真实姓名"
        />
      </a-form-item>
      <a-form-item label="手机号">
        <a-input v-model:value="formData.phone" placeholder="请输入手机号" />
      </a-form-item>
      <a-form-item label="邮箱">
        <a-input v-model:value="formData.email" placeholder="请输入邮箱" />
      </a-form-item>
      <a-form-item label="角色">
        <a-select
          v-model:value="formData.roleId"
          placeholder="请选择角色"
          allowClear
          :disabled="isEdit && isAdminUser(formData as any)"
        >
          <a-select-option
            v-for="role in roleList"
            :key="role.id"
            :value="role.id"
            :disabled="role.isSystem === 1"
          >
            {{ role.roleName }}
            <span
              v-if="role.isSystem === 1"
              style="color: var(--text-secondary); margin-left: 8px"
            >
              （管理员角色，已存在管理员用户）
            </span>
          </a-select-option>
        </a-select>
        <div
          v-if="!isEdit"
          style="margin-top: 8px; font-size: 12px; color: var(--text-secondary)"
        >
          注意：每个租户只能有一个管理员用户
        </div>
      </a-form-item>
      <a-form-item label="状态">
        <a-switch v-model:checked="formData.statusChecked" />
      </a-form-item>
    </a-form>
  </a-modal>

  <!-- 重置密码弹窗 -->
  <a-modal
    v-model:open="resetPasswordVisible"
    title="重置密码"
    @ok="handleResetPasswordSubmit"
    @cancel="resetPasswordVisible = false"
  >
    <a-form :label-col="{ span: 6 }">
      <a-form-item label="新密码" required>
        <a-input-password
          v-model:value="newPassword"
          placeholder="请输入新密码"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { message } from "ant-design-vue";
import { PlusOutlined } from "@ant-design/icons-vue";
import PageContainer from "@/components/business/PageContainer.vue";
import type { User, UserFormData } from "@/types/user";
import type { Role } from "@/types/role";
import {
  getUserList,
  createUser,
  updateUser,
  deleteUser,
  updateUserStatus,
  resetPassword,
} from "@/api/tenant/user";
import { getRoleList } from "@/api/tenant/role";
import dayjs from "dayjs";

const loading = ref(false);
const userList = ref<User[]>([]);
const roleList = ref<Role[]>([]);

const queryParams = reactive({
  keyword: "",
  status: undefined as number | undefined,
});

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  pageSizeOptions: ["10", "20", "50", "100"],
});

// 页面操作按钮配置
const pageActions = computed(() => [
  {
    key: "create",
    label: "新增用户",
    type: "primary" as const,
    icon: PlusOutlined,
    permission: "b8f1p6j4",
    onClick: handleCreate,
  },
]);

const columns = [
  { title: "用户名", dataIndex: "username", key: "username", width: 180 },
  { title: "真实姓名", dataIndex: "realName", key: "realName", width: 150 },
  { title: "角色", dataIndex: "roleName", key: "roleName", width: 120 },
  { title: "状态", dataIndex: "status", key: "status", width: 100 },
  {
    title: "最后登录时间",
    dataIndex: "lastLoginTime",
    key: "lastLoginTime",
    width: 180,
  },
  { title: "操作", key: "action", width: 280, fixed: "right" as const },
];

// 弹窗相关
const modalVisible = ref(false);
const isEdit = ref(false);
const modalTitle = computed(() => (isEdit.value ? "编辑用户" : "新增用户"));
const formData = reactive<UserFormData & { statusChecked?: boolean }>({
  username: "",
  password: "",
  realName: "",
  phone: "",
  email: "",
  roleId: undefined,
  status: 1,
  statusChecked: true,
});

// 重置密码相关
const resetPasswordVisible = ref(false);
const resetPasswordUserId = ref<number>();
const newPassword = ref("");

onMounted(() => {
  fetchUserList();
  fetchRoleList();
});

const fetchUserList = async () => {
  try {
    loading.value = true;
    const res = await getUserList({
      current: pagination.current,
      size: pagination.pageSize,
      ...queryParams,
    });
    const data = res.data as any;
    userList.value = data.records || [];
    pagination.total = data.total || 0;
  } catch (error) {
    console.error("获取用户列表失败:", error);
  } finally {
    loading.value = false;
  }
};

const fetchRoleList = async () => {
  try {
    const res = await getRoleList({ current: 1, size: 100 });
    const data = res.data as any;
    roleList.value = data.records || [];
  } catch (error) {
    console.error("获取角色列表失败:", error);
  }
};

const handleSearch = () => {
  pagination.current = 1;
  fetchUserList();
};

const handleReset = () => {
  Object.assign(queryParams, {
    keyword: "",
    status: undefined,
  });
  pagination.current = 1;
  fetchUserList();
};

const handlePaginationChange = (page: number, pageSize: number) => {
  pagination.current = page;
  pagination.pageSize = pageSize;
  fetchUserList();
};

const handleCreate = () => {
  isEdit.value = false;
  modalVisible.value = true;
  Object.assign(formData, {
    username: "",
    password: "",
    realName: "",
    phone: "",
    email: "",
    roleId: undefined,
    status: 1,
    statusChecked: true,
  });
};

const handleEdit = (record: User) => {
  isEdit.value = true;
  modalVisible.value = true;
  Object.assign(formData, {
    id: record.id,
    username: record.username,
    realName: record.realName,
    phone: record.phone || "",
    email: record.email || "",
    roleId: record.roleId,
    status: record.status,
    statusChecked: record.status === 1,
  });
};

const handleSubmit = async () => {
  try {
    const data: any = {
      username: formData.username,
      realName: formData.realName,
      phone: formData.phone,
      email: formData.email,
      roleId: formData.roleId,
      status: formData.statusChecked ? 1 : 0,
    };

    if (!isEdit.value) {
      if (!formData.password) {
        message.error("请输入密码");
        return;
      }
      data.password = formData.password;
    }

    if (isEdit.value && formData.id) {
      await updateUser(formData.id, data);
      message.success("更新成功");
    } else {
      await createUser(data);
      message.success("创建成功");
    }

    modalVisible.value = false;
    fetchUserList();
  } catch (error: any) {
    message.error(error.message || "操作失败");
  }
};

const handleCancel = () => {
  modalVisible.value = false;
};

const handleDelete = async (id: number) => {
  try {
    await deleteUser(id);
    message.success("删除成功");
    fetchUserList();
  } catch (error: any) {
    message.error(error.message || "删除失败");
  }
};

const handleToggleStatus = async (record: User) => {
  try {
    const newStatus = record.status === 1 ? 0 : 1;
    await updateUserStatus(record.id, { status: newStatus });
    message.success(newStatus === 1 ? "已启用" : "已禁用");
    fetchUserList();
  } catch (error: any) {
    message.error(error.message || "操作失败");
  }
};

const handleResetPassword = (record: User) => {
  resetPasswordUserId.value = record.id;
  newPassword.value = "";
  resetPasswordVisible.value = true;
};

const handleResetPasswordSubmit = async () => {
  if (!newPassword.value) {
    message.error("请输入新密码");
    return;
  }

  try {
    await resetPassword(resetPasswordUserId.value!, {
      newPassword: newPassword.value,
    });
    message.success("密码重置成功");
    resetPasswordVisible.value = false;
  } catch (error: any) {
    message.error(error.message || "密码重置失败");
  }
};

const formatDateTime = (dateTime: string | undefined) => {
  if (!dateTime) return "-";
  return dayjs(dateTime).format("YYYY-MM-DD HH:mm:ss");
};

// 判断是否是“系统级管理员”用户
// 仅顶级管理员账号（平台超级管理员 / 租户超级管理员）视为系统管理员：
// - 只能重置密码
// - 不在前端展示编辑 / 删除按钮（后端仍会做权限校验）
const isAdminUser = (user: User) => {
  const adminRoles = ["平台超级管理员", "超级管理员"];
  return adminRoles.includes(user.roleName || "");
};
</script>

<style scoped>
/* 用户信息样式 */
.user-email,
.user-phone {
  font-size: 12px;
  color: var(--text-secondary);
  margin-top: 4px;
}

/* 管理员提示样式 */
.admin-tip {
  margin-top: 4px;
  font-size: 12px;
}
</style>
